package org.example.shop.controller;

import org.example.shop.entity.Goods;
import org.example.shop.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
@Controller
public class IndexController {
    @Autowired
    private GoodsService goodsService;

    @RequestMapping("/")
    public String index(
            Model model,
            @RequestParam(defaultValue = "1") int page) {
        long total = goodsService.count();
        int totalPages = (int) Math.ceil((double) total / 12);
        if (page < 1) page = 1;
        if (page > totalPages) page = totalPages;
        List<Goods> newGoodsList = goodsService.findByPage(page, 12);

        List<Goods> hotGoodsList = goodsService.selectHotRandom();

        model.addAttribute("newgoods", newGoodsList);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("total", total);
        model.addAttribute("hotGoods", hotGoodsList);

        return "index";
    }
}